import { forwardRef, useImperativeHandle, useReducer } from 'react'
import { Root } from './context'
import reducer from './reducer'
//表单组件
const Form = forwardRef((props, ref) => {
  const [state, dispatch] = useReducer(reducer, {})
  const { children, style = {}, className } = props;
  useImperativeHandle(ref, () => ({
    // 验证是否输入了所有的字段，如果有未输入字段则显示警告
    onVerify (newState) {
      dispatch({
        type: 'changeValue',
        payload: newState
      })
    },
    // 获取所有输入的值
    onSubmit () {
      return state
    },
    //登录函数
    async onSignIn (url) {
      return fetch(url, {
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(state)
      }).then(res => res.json()).then(data => data)
    },
    //注册函数
    async onSignUp (url) {
      return fetch(url, {
        method: "post",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(state)
      }).then(res => res.json()).then(data => data)
    },
  }))
  return (
    <div style={{ ...style }} className={className}>
      <Root value={{
        state,
        dispatch
      }}>
        {children}
      </Root>
    </div>
  )
});
export default Form;